<?php
if (php_sapi_name() !== 'cli')  exit(404);

/**
 * WordPress 数据库操作工具类
 * 封装常用的 WordPress 数据库操作
 */
class WPSqlTool
{
    private $conn;
    private $last_error = '';
    private $table_prefix;

    /**
     * 构造函数，初始化数据库连接
     * 
     * @param string $servername 数据库服务器
     * @param string $username 数据库用户名
     * @param string $password 数据库密码
     * @param string $dbname 数据库名
     * @param string $table_prefix 数据表前缀，默认'wp_'
     */
    public function __construct($servername, $username, $password, $dbname, $table_prefix = 'wp_')
    {
        $this->conn = new mysqli($servername, $username, $password, $dbname);

        if ($this->conn->connect_error) {
            $this->last_error = "Connection failed: " . $this->conn->connect_error;
            throw new Exception($this->last_error);
        }

        $this->table_prefix = $table_prefix;
    }

    /**
     * 获取最后一条错误信息
     */
    public function getLastError()
    {
        return $this->last_error;
    }

    /**
     * 安全转义字符串
     */
    private function escape($value)
    {
        return $this->conn->real_escape_string($value);
    }

    //添加一个方法，获取分类数据
    /**
     * 获取所有分类数据
     * 
     * @return array 返回分类数组，每个元素包含 term_id, name, slug, description, parent
     */
    public function getCategroies()
    {
        $categories = [];
        $sql = "SELECT t.term_id, t.name, t.slug, tt.description, tt.parent 
            FROM {$this->table_prefix}terms t
            INNER JOIN {$this->table_prefix}term_taxonomy tt ON t.term_id = tt.term_id
            WHERE tt.taxonomy = 'category'";

        $result = $this->conn->query($sql);

        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $categories[] = $row;
            }
        }

        return $categories;
    }



    /**
     * 创建分类
     * 
     * @param string $name 分类名称
     * @param string $slug 分类别名(可选)
     * @param string $description 分类描述(可选)
     * @param int $parent_id 父分类ID(可选)
     * @return int|false 成功返回分类ID，失败返回false
     */
    /**
     * 创建分类（避免重复插入）
     * 
     * @param string $name 分类名称
     * @param string $slug 分类别名(可选)
     * @param string $description 分类描述(可选)
     * @param int $parent_id 父分类ID(可选)
     * @return int|false 成功返回分类ID，失败返回false
     */
    public function createCategory($name, $slug = '', $description = '', $parent_id = 0)
    {
        $name = $this->escape($name);
        $slug = $slug ? $this->escape($slug) : sanitize_title($name);
        $description = $this->escape($description);
        $parent_id = (int)$parent_id;

        // 先检查分类是否已存在
        $existing_term = $this->getTermBySlug($slug, 'category');
        if ($existing_term) {
            // 分类已存在，返回现有ID
            return $existing_term['term_id'];
        }

        // 开始事务
        $this->conn->begin_transaction();

        try {
            // 插入wp_terms表
            $sql = "INSERT INTO {$this->table_prefix}terms (name, slug) VALUES ('$name', '$slug')";
            if (!$this->conn->query($sql)) {
                throw new Exception("Error inserting term: " . $this->conn->error);
            }

            $term_id = $this->conn->insert_id;

            // 插入wp_term_taxonomy表
            $sql = "INSERT INTO {$this->table_prefix}term_taxonomy 
                (term_id, taxonomy, description, parent) 
                VALUES ('$term_id', 'category', '$description', '$parent_id')";

            if (!$this->conn->query($sql)) {
                throw new Exception("Error inserting term taxonomy: " . $this->conn->error);
            }

            $this->conn->commit();
            return $term_id;
        } catch (Exception $e) {
            $this->conn->rollback();
            $this->last_error = $e->getMessage();
            return false;
        }
    }

    /**
     * 根据slug获取分类/标签信息
     * 
     * @param string $slug 别名
     * @param string $taxonomy 分类法类型（category/post_tag等）
     * @return array|false 成功返回分类信息数组，失败返回false
     */
    private function getTermBySlug($slug, $taxonomy = 'category')
    {
        $slug = $this->escape($slug);
        $taxonomy = $this->escape($taxonomy);

        $sql = "SELECT t.term_id, t.name, t.slug, tt.term_taxonomy_id, tt.description, tt.parent 
            FROM {$this->table_prefix}terms t
            INNER JOIN {$this->table_prefix}term_taxonomy tt ON t.term_id = tt.term_id
            WHERE t.slug = '$slug' AND tt.taxonomy = '$taxonomy'";

        $result = $this->conn->query($sql);

        if ($result && $result->num_rows > 0) {
            return $result->fetch_assoc();
        }

        return false;
    }


    /**
     * 创建标签
     * 
     * @param string $name 标签名称
     * @param string $slug 标签别名(可选)
     * @param string $description 标签描述(可选)
     * @return int|false 成功返回标签ID，失败返回false
     */
    /**
     * 根据slug获取分类/标签信息
     * 
     * @param string $slug 别名
     * @param string $taxonomy 分类法类型（category/post_tag等）
     * @return array|false 成功返回分类信息数组，失败返回false
     */


    /**
     * 创建标签（避免重复插入）
     * 
     * @param string $name 标签名称
     * @param string $slug 标签别名(可选)
     * @param string $description 标签描述(可选)
     * @return int|false 成功返回标签ID，失败返回false
     */
    public function createTag($name, $slug = '', $description = '')
    {
        $name = $this->escape($name);
        $slug = $slug ? $this->escape($slug) : sanitize_title($name);
        $description = $this->escape($description);

        // 先检查标签是否已存在
        $existing_term = $this->getTermBySlug($slug, 'post_tag');
        if ($existing_term) {
            // 标签已存在，返回现有ID
            return $existing_term['term_id'];
        }

        // 开始事务
        $this->conn->begin_transaction();

        try {
            // 插入wp_terms表
            $sql = "INSERT INTO {$this->table_prefix}terms (name, slug) VALUES ('$name', '$slug')";
            if (!$this->conn->query($sql)) {
                throw new Exception("Error inserting term: " . $this->conn->error);
            }

            $term_id = $this->conn->insert_id;

            // 插入wp_term_taxonomy表
            $sql = "INSERT INTO {$this->table_prefix}term_taxonomy 
                (term_id, taxonomy, description) 
                VALUES ('$term_id', 'post_tag', '$description')";

            if (!$this->conn->query($sql)) {
                throw new Exception("Error inserting term taxonomy: " . $this->conn->error);
            }

            $this->conn->commit();
            return $term_id;
        } catch (Exception $e) {
            $this->conn->rollback();
            $this->last_error = $e->getMessage();
            return false;
        }
    }


    /**
     * 创建文章
     * 
     * @param array $post_data 文章数据数组
     * @param array $term_ids 分类/标签ID数组
     * @return int|false 成功返回文章ID，失败返回false
     */
    public function createPost($post_data, $term_ids = [])
    {
        // 默认值设置
        $defaults = [
            'post_author' => 1,
            'post_date' => current_time('mysql'),
            'post_date_gmt' => current_time('mysql', 1),
            'post_content' => '',
            'post_content_filtered' => '',  // 新增
            'post_title' => '',
            'post_excerpt' => '',
            'post_status' => 'publish',
            'comment_status' => 'open',
            'ping_status' => 'open',
            'post_name' => '',
            'post_modified' => current_time('mysql'),
            'post_modified_gmt' => current_time('mysql', 1),
            'post_type' => 'post',
            'post_parent' => 0,
            'menu_order' => 0,
            'to_ping' => '',
            'pinged' => ''
        ];

        $post_data = array_merge($defaults, $post_data);

        // 转义数据
        foreach ($post_data as $key => $value) {
            if (is_string($value)) {
                $post_data[$key] = $this->escape($value);
            }
        }

        // 如果没有设置post_name，根据标题生成
        if (empty($post_data['post_name'])) {
            $post_data['post_name'] = sanitize_title($post_data['post_title']);
        }

        // 开始事务
        $this->conn->begin_transaction();

        try {
            // 插入文章
            $sql = "INSERT INTO {$this->table_prefix}posts (
                post_author, post_date, post_date_gmt, post_content, 
                post_content_filtered, post_title, post_excerpt, post_status, 
                comment_status, ping_status, post_name, post_modified, 
                post_modified_gmt, post_type, post_parent, menu_order, 
                to_ping, pinged
            ) VALUES (
                '{$post_data['post_author']}', '{$post_data['post_date']}', '{$post_data['post_date_gmt']}', 
                '{$post_data['post_content']}', '{$post_data['post_content_filtered']}', 
                '{$post_data['post_title']}', '{$post_data['post_excerpt']}', 
                '{$post_data['post_status']}', '{$post_data['comment_status']}', 
                '{$post_data['ping_status']}', '{$post_data['post_name']}', 
                '{$post_data['post_modified']}', '{$post_data['post_modified_gmt']}', 
                '{$post_data['post_type']}', '{$post_data['post_parent']}', 
                '{$post_data['menu_order']}', '{$post_data['to_ping']}', 
                '{$post_data['pinged']}'
            )";

            if (!$this->conn->query($sql)) {
                throw new Exception("Error inserting post: " . $this->conn->error);
            }

            $post_id = $this->conn->insert_id;

            // 关联分类/标签
            if (!empty($term_ids)) {
                foreach ($term_ids as $term_id) {
                    // 获取term_taxonomy_id
                    $sql = "SELECT term_taxonomy_id FROM {$this->table_prefix}term_taxonomy WHERE term_id = " . (int)$term_id;
                    $result = $this->conn->query($sql);

                    if ($result && $result->num_rows > 0) {
                        $row = $result->fetch_assoc();
                        $term_taxonomy_id = $row['term_taxonomy_id'];

                        // 插入关联关系
                        $sql = "INSERT INTO {$this->table_prefix}term_relationships 
                                (object_id, term_taxonomy_id) 
                                VALUES ('$post_id', '$term_taxonomy_id')";

                        if (!$this->conn->query($sql)) {
                            throw new Exception("Error linking term to post: " . $this->conn->error);
                        }
                    }
                }
            }

            $this->conn->commit();
            return $post_id;
        } catch (Exception $e) {
            $this->conn->rollback();
            $this->last_error = $e->getMessage();
            return false;
        }
    }



    /**
     * 关闭数据库连接
     */
    public function close()
    {
        if ($this->conn) {
            $this->conn->close();
        }
    }

    /**
     * 析构函数，自动关闭连接
     */
    public function __destruct()
    {
        $this->close();
    }
}

/**
 * 辅助函数：生成 WordPress 友好的 URL slug
 */
function sanitize_title($title)
{
    $title = preg_replace('/[^a-z0-9\-]/', '-', strtolower($title));
    $title = preg_replace('/-+/', '-', $title);
    return trim($title, '-');
}

/**
 * 辅助函数：获取当前时间，格式化为MySQL日期时间格式
 */
function current_time($type = 'mysql', $gmt = 0)
{
    return date("Y-m-d H:i:s", time() - random_int(0, 2 * 60 * 60));
}

function scanTxtFiles($directory)
{
    $txtFiles = [];
    if (!is_dir($directory)) {
        return $txtFiles;
    }
    $items = scandir($directory);

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $path = $directory . DIRECTORY_SEPARATOR . $item;
        if (is_dir($path)) {
            $txtFiles = array_merge($txtFiles, scanTxtFiles($path));
        } elseif (is_file($path) && pathinfo($path, PATHINFO_EXTENSION) === 'txt' && mb_strlen(trim($item, '.txt')) > 5) {
            $txtFiles[] = [
                'title' => $item,
                'path' => $path
            ];
        }
    }
    return $txtFiles;
}
function processTxtFiles(WPSqlTool $wpdb, $directory, $catIds = [],$num = 0)
{
    $txtFiles = scanTxtFiles($directory);
    $imgs = array_slice(scandir(__DIR__ . "/../uploads/imgs"), 2);

    if($num > 0){
        $num = count($catIds) * $num;
        $txtFiles = array_chunk($txtFiles, $num)[0];
    }

    foreach ($txtFiles as $k => $item) {
        $content = file_get_contents($item['path']);
        $content = trim(preg_replace('/[\r\n\t]+/', '', $content));
        $content = preg_replace('/<a[^>]*>(.*?)<\/a>/i', '', $content);
        $content = preg_replace('/<img[^>]*>/i', '', $content);

        $title =  trim($item['title'], '.txt');

        $randomImgs = array_rand($imgs, 3);
        $contentParts = explode('</p>', $content);
        $modifiedContent = '';
        foreach ($contentParts as $index => $part) {
            $modifiedContent .= $part . '</p>';
            if ($index < 3) {
                $modifiedContent .= '<img src="/wp-content/uploads/imgs/' . htmlspecialchars($imgs[$randomImgs[$index]]) . '" title="{$title}" />' . PHP_EOL;
            }
        }
        $content = $modifiedContent;
        $post_id = $wpdb->createPost([
            'post_title' => $title,
            'post_content' => $content,
            'post_excerpt' => mb_substr(strip_tags($content), 0, 100),
            'post_status' => 'publish'
        ], [$catIds[($k + 1) % count($catIds)]]);

        if ($post_id === false) {
            echo "创建文章失败: " . $wpdb->getLastError() . "\n";
        } else {
            echo "文章创建成功，ID: $post_id\n";

            //添加成功后删除文件
            unlink($item['path']);
        }        
    }
    echo 'Processing complete.' . PHP_EOL;
}







function  createCats(WPSqlTool $wpdb, array $cats = [])
{

    if (empty($cats)) {
        echo "没有分类数据\n";
        return;
    }
    if (empty($cats)) {
        echo "没有分类数据\n";
        return;
    }


    $catIds = [];
    // 创建分类
    foreach ($cats as $cat) {
        $category_id = $wpdb->createCategory(
            $cat['name'] ?? $cat['nicename'],
            $cat['nicename'],
            $cat['name'] ?? $cat['nicename'],
            0
        );

        if ($category_id === false) {
            echo "创建分类失败: " . $wpdb->getLastError() . "\n";
        } else {
            echo "分类创建成功，ID: $category_id\n";
            $catIds[] = $category_id;
        }
    }
    return $catIds;
}


function addCatArticles(string $prefix,string $inputDir,int $num = 0,array $cats = []){
    $tablePrefix = $prefix;
    $db = new WPSqlTool('127.0.0.1', 'root', '123465', 'wp', $tablePrefix);

    if($cats){
        $catIds = createCats($db, $cats);
    } else {
        $catIds = array_column($db->getCategroies(), 'term_id');
    }

    processTxtFiles($db, $inputDir, $catIds,$num);
}


addCatArticles("wp_","/mnt/d/articles/inputs/date20250707",1);
